﻿#region Header
// Copyright 2007-2011, Jerónimo Milea
// 
// This file is part of NetJsWire.
// 
//     NetJsWire is free software: you can redistribute it and/or modify
//     it under the terms of the GNU General Public License as published by
//     the Free Software Foundation, either version 3 of the License, or
//     (at your option) any later version.
// 
//     NetJsWire is distributed in the hope that it will be useful,
//     but WITHOUT ANY WARRANTY; without even the implied warranty of
//     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//     GNU General Public License for more details.
// 
//     You should have received a copy of the GNU General Public License
//     along with NetJsWire.  If not, see <http://www.gnu.org/licenses/>.
#endregion

using System;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Globalization;
using System.Windows.Forms;
using NetJsWire.Lite.Widgets;

namespace NetJsWire.Lite.Converters
{
    public class ListenerTypeConverter : TypeConverter// ExpandableObjectConverter
    {
        public override bool CanConvertFrom( ITypeDescriptorContext context, Type sourceType )
        {
            return sourceType == typeof( InstanceDescriptor ) || base.CanConvertFrom( context, sourceType );
        }

        public override object ConvertTo( ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType )
        {
            if ( destinationType == null )
            {
                throw new ArgumentNullException( "destinationType" );
            }
            var listener = value as Listener;
            if ( destinationType == typeof( InstanceDescriptor ) && listener != null )
            {
                MessageBox.Show( "Llega" );
                var parameters = new object[ 4 ] { listener.EventName, listener.Handler, listener.Scope, listener.Options };
                var types = new Type[ 4 ] { typeof( string ), typeof( string ), typeof( string ), typeof( EventOptions ) };
                if ( !string.IsNullOrWhiteSpace( listener.EventName ) || !string.IsNullOrWhiteSpace( listener.Handler ) )
                {
                    return new InstanceDescriptor( typeof( Listener ).GetConstructor( types ), parameters, true );
                }
                else
                {
                    return new InstanceDescriptor( typeof( Listener ).GetConstructor( new Type[ 0 ] ), null, false );
                }
            }
            return base.ConvertTo( context, culture, value, destinationType );
        }

        public override object CreateInstance( ITypeDescriptorContext context, System.Collections.IDictionary propertyValues )
        {
            
            return base.CreateInstance( context, propertyValues );
        }
    }
}
